// FILEPATH: src/modules/rally-rule/rally-rule.service.ts

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateRallyRuleDto } from './dto/create-rally-rule.dto';
import { UpdateRallyRuleDto } from './dto/update-rally-rule.dto';
import { RallyRule } from './entities/rally-rule.entity';

@Injectable()
export class RallyRuleService {
  constructor(
    @InjectRepository(RallyRule)
    private rallyRuleRepository: Repository<RallyRule>,
  ) {}

  async create(createrallyRuleDto: CreateRallyRuleDto): Promise<RallyRule> {
    const rallyRule = this.rallyRuleRepository.create(createrallyRuleDto);
    return await this.rallyRuleRepository.save(rallyRule);
  }

  async findAll(): Promise<RallyRule[]> {
    return await this.rallyRuleRepository.find();
  }

  async findOne(id: number): Promise<RallyRule> {
    const rallyRule = await this.rallyRuleRepository.findOne({
      where: { id },
    });
    if (!rallyRule) {
      throw new NotFoundException(`rally rule with ID ${id} not found`);
    }
    return rallyRule;
  }

  async update(
    id: number,
    updateRallyRuleDto: UpdateRallyRuleDto,
  ): Promise<RallyRule> {
    const rallyRule = await this.findOne(id);
    Object.assign(rallyRule, updateRallyRuleDto);
    return await this.rallyRuleRepository.save(rallyRule);
  }

  async remove(id: number): Promise<void> {
    const result = await this.rallyRuleRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`rally rule with ID ${id} not found`);
    }
  }
}
